package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"kf/models/dao"
	"kf/models/entity"
	"kf/utils/R"
	"net/http"
	"strconv"
)

type MenusController struct {
	MenuDao *dao.SysMenuDao
	Log     *zap.Logger
}

func (menusController *MenusController) GetMenus(c *gin.Context) {
	var menuQuery entity.MenuQuery
	err := c.ShouldBindQuery(&menuQuery)
	if err != nil {
		c.JSON(http.StatusInternalServerError, "获取菜单失败")
		return
	}
	list, err := menusController.MenuDao.GetMenus(menuQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

// 获取路由
func (menusController *MenusController) RoutesV1(c *gin.Context) {
	roleId, _ := c.Get("role_id")
	zap.Any("roleId", roleId)
	var roleList []string
	roleList = append(roleList, "ROOT")
	routes, err := menusController.MenuDao.ListRoutes(roleList)
	if err != nil {
		menusController.Log.Error("获取路由失败", zap.Error(err))
		c.JSON(http.StatusInternalServerError, R.ReturnSuccess(err))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(routes))
}

func (menusController *MenusController) ListMenuOptions(context *gin.Context) {

	routes, err := menusController.MenuDao.ListMenuOptions()
	if err != nil {
		context.JSON(http.StatusInternalServerError, R.ReturnSuccess(err))
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(routes))
}

func (menusController *MenusController) GetMenuForm(context *gin.Context) {
	menuIdStr := context.Param("menuId")
	// 尝试将字符串转换为整数
	menuId, err := strconv.ParseUint(menuIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		context.JSON(http.StatusInternalServerError, "Invalid ID")
		return
	}
	form, err := menusController.MenuDao.GetMenuForm(menuId)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(form))
}

func (menusController *MenusController) UpdateMenu(context *gin.Context) {
	var menuForm entity.MenuForm
	err := context.ShouldBindJSON(&menuForm)
	if err != nil {
		menusController.Log.Error("转换失败", zap.Error(err))
		context.JSON(http.StatusInternalServerError, "修改参数失败")
		return
	}
	result, err := menusController.MenuDao.SaveMenu(menuForm)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}

// 删除
func (menusController *MenusController) DeleteMenu(context *gin.Context) {
	idStr := context.Param("id")
	b, err := menusController.MenuDao.DeleteMenu(idStr)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(b))
}
